package com.shop.AliPay;

import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.StringUtils;
import com.shop.result.PayJsonResult;
import com.shop.service.impl.AliPayServiceImpl;
import com.shop.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/payment")
public class AlipayController {

    @Autowired
    private AliPayServiceImpl aliPayServiceImpl;

    /*支付功能测试页面*/
    @GetMapping("/index")
    public String index(HttpServletRequest request,HttpServletResponse response)throws Exception{
        return "index";
    }

    /*支付功能测试接口*/
    @PostMapping("/goAliPay")
    public String goAliPay(HttpServletRequest request, Model model)throws Exception{
        String merchantUserId = request.getParameter("merchantUserId");
        String merchantOrderId = request.getParameter("merchantOrderId");
        Map<String,Object> params = new HashMap<>();
        params.put("merchantUserId",merchantUserId);
        params.put("merchantUserName","胡金水");
        params.put("merchantOrderId",merchantOrderId);
        params.put("totalMoney",0.01);

        PayJsonResult data = aliPayServiceImpl.goAlipay(params);
        String formData = data.getData().toString();
        model.addAttribute("formData",formData);

        return "goAliPay";
    }

    /**
     * 支付成功后的支付宝异步通知
     */
    @RequestMapping(value="/alipayResult")
    public void alipayResult(HttpServletRequest request, HttpServletResponse response) throws Exception {
        aliPayServiceImpl.alipayResult(request);
    }

    /**
     * 支付成功后的支付宝返回通知
     */
    @RequestMapping(value="/alipayReturn")
    public String alipayReturn(HttpServletRequest request, HttpServletResponse response,Model model) throws Exception {
        String msg = aliPayServiceImpl.alipayReturn(request);
        model.addAttribute("msg",msg);

        return "payReturn";
    }

}
